import pymysql

from config.setting import pool


def get_user_token(token):
    conn = None
    try:
        conn = pool.connection()  # 从数据库获取连接
        with conn.cursor() as cursor:
            cursor.execute("SELECT * FROM db_user WHERE token = %s", (token,))
            return cursor.fetchone()
    finally:
        if conn:
            conn.close()  # 释放连接(放回连接池，非真正关闭)


def insert_batch_data(pool, dict_list):
    if not pool or not dict_list:
        return False
    conn = pool.connection()

    try:

        # 创建游标对象（用于执行SQL）
        raw_conn = conn._con  # 关键：获取pymysql原始连接
        cursor = raw_conn.cursor()
        # 从第一个字典中获取键 (假设所有的字典结构相同)
        keys = ",".join(dict_list[0].keys())
        placeholders = ",".join([f"%({k})s" for k in dict_list[0].keys()])

        sql = f"""
        INSERT INTO geography ({keys}) VALUES ({placeholders})
        """

        # 批量执行 (传入字典列表)
        cursor.executemany(sql, dict_list)
        raw_conn.commit()
        print(f"批量插入成功,共{cursor.rowcount} 条")
        return True
    except pymysql.Error as e:
        print(f"批量插入失败:{e}")
        raw_conn.rollback()
        return False
    finally:
        if 'cursor' in locals():
            cursor.close()
        if 'conn' in locals():
            conn.close()


if __name__ == '__main__':
    # print(get_user_token("b546d0bc-3376-469f-a9ad-8ed830626f6e"))
    insert_batch_data(pool, [
        {'name': 'starbucks', 'latitude': 66.606415, 'longitude': 8.536282, 'types': 'restaurant'},
        {'name': 'starbucks', 'latitude': -78.14681, 'longitude': 38.99839, 'types': 'mall'},
        {'name': 'kfc', 'latitude': -4.453473, 'longitude': -62.734004, 'types': 'mall'},
        {'name': 'starbucks', 'latitude': -69.998812, 'longitude': -14.766053, 'types': 'shop'},
        {'name': 'kfc', 'latitude': -63.20177, 'longitude': -8.461464, 'types': 'shop'},
        {'name': 'starbucks', 'latitude': -29.035083, 'longitude': -21.518875, 'types': 'mall'},
        {'name': 'mcd', 'latitude': -48.208764, 'longitude': -26.731161, 'types': 'shop'}])
